package mybatisgen.demo.service;

import cn.hutool.core.io.FileUtil;
import org.apache.velocity.VelocityContext;
import org.apache.velocity.app.VelocityEngine;
import org.apache.velocity.runtime.RuntimeConstants;
import org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader;

import java.io.*;
import java.util.UUID;

public class ExecTemp {
    private static final String GLOBAL_CODE_DIR_NAME = "tmpCode";

    public static ByteArrayInputStream getInputStream(String tableName, DataBase dataBase) {
        // 创建一个上下文并设置变量
        String prefix = "gender.com.xinmei." + dataBase.getSysCode();
        VelocityContext context = new VelocityContext();
        context.put("jdbc_mysql_url", dataBase.getUrl());
        context.put("jdbc_mysql_userId", dataBase.getName());
        context.put("jdbc_mysql_password", dataBase.getPassword());
        context.put("target_package_dto", prefix + ".dto");
        context.put("target_package", prefix);
        context.put("target_package_dao", prefix + ".dao");
        context.put("target_package_mapper", prefix + ".mapper");
        context.put("table_name", tableName);
        String camelCase = NamingConventionUtils.convertToCamelCase(tableName);
        context.put("domain_object_name", camelCase + "DO");
        context.put("domain_object", camelCase);
        context.put("dao_name_object", uncapitalizeFirstLetter(camelCase));
        String xmlConfig = getString(context, "mapper.xml.vm");
        String string1 = getString(context, "service.Java.vm");
        String string2 = getString(context, "serviceImpl.Java.vm");
        String userDir = System.getProperty("user.dir");
        String projectRoot = userDir + File.separator + "\\src\\main\\java\\";
        String replacement = "\\\\";
        String filePath = projectRoot + prefix.replaceAll("\\.", replacement) + "\\\\service\\\\";
        if (!FileUtil.exist(filePath)) {
            FileUtil.mkdir(filePath);
        }
        extracted(filePath + camelCase + "Service.java", string1);
        extracted(filePath + camelCase + "ServiceImpl.java", string2);
        return new ByteArrayInputStream(xmlConfig.getBytes());
    }
    public static String uncapitalizeFirstLetter(String input) {
        if (input == null || input.isEmpty()) {
            return input;
        }
        if (input.length() == 1) {
            return input.toLowerCase();
        }
        return Character.toLowerCase(input.charAt(0)) + input.substring(1);
    }
    private static void extracted(String filePath, String string1) {
        try (BufferedWriter writer = new BufferedWriter(new FileWriter(filePath))) {
            writer.write(string1);
            System.out.println("File created successfully at " + filePath);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private static String getString(VelocityContext context, String vmName) {
        // 合并模板与上下文
        StringWriter writer = new StringWriter();
        VelocityEngine velocityEngine = new VelocityEngine();
        velocityEngine.setProperty(RuntimeConstants.RESOURCE_LOADER, "classpath");
        velocityEngine.setProperty("classpath.resource.loader.class", ClasspathResourceLoader.class.getName());
        velocityEngine.init();
        // 加载模板
        velocityEngine.getTemplate(vmName).merge(context, writer);
//        writeFile(writer);
        String string = writer.toString();
        return string;
    }


    private static void writeFile(StringWriter writer) {
        String userDir = System.getProperty("user.dir");
        String globalCodePathName = userDir + File.separator + GLOBAL_CODE_DIR_NAME;
        // 判断全局代码目录是否存在，没有则新建
        String userCodeParentPath = globalCodePathName + File.separator + UUID.randomUUID();
        if (!FileUtil.exist(userCodeParentPath)) {
            FileUtil.mkdir(userCodeParentPath);
        }
        // 把用户的代码隔离存放
        String userCodePath = userCodeParentPath + File.separator + "output.xml";
        System.out.println("output.xml output to " + userCodePath);
        // 输出到XML文件
        try (FileWriter fw = new FileWriter(userCodePath)) {
            fw.write(writer.toString());
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
